package net.csdn.business.mirror.utils;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class UrlUtil {
    public static String getNewUrl(String url, Map<String, String> params) {
        if (StringUtils.isEmpty(url) || Objects.isNull(params) || params.isEmpty()) {
            return url;
        }
        String[] urlArr = url.split("\\?");
        Map<String, String> urlParams = new HashMap<>();
        if (urlArr.length == 2 && StringUtils.isNotEmpty(urlArr[1])) {
            for (Map.Entry<String, String> p : Splitter.on("&").withKeyValueSeparator("=").split(urlArr[1]).entrySet()) {
                urlParams.put(p.getKey(), p.getValue());
            }
        }
        for (Map.Entry<String, String> p : params.entrySet()) {
            urlParams.put(p.getKey(), p.getValue());
        }
        return urlArr[0] + "?" + Joiner.on("&").withKeyValueSeparator("=").join(urlParams);
    }
}
